<?php
namespace App\Services;

use App\Models\HhmOrder as Order;
use App\Models\BreedUserCoin;
use App\Models\Store;
use App\Models\Member;
use App\Models\RegionProvinceAgent;
use App\Models\RegionCityAgent;
use App\Models\RegionCityDistrictAgent;
use App\Models\DistrictAgentCommissionConfig;
use App\Models\HhmOrderGoods as OrderGoods;
use App\Models\BreedCoinFlow as BreedCoinFlows;
use App\Models\Lovemember as MemberLove;
use App\Models\CountyGroup;
use App\Models\BreedCommissionCoinFlow;
use App\Models\Address as Area;
class OrderCommonService
{
    /**
     * 代理分成
     */
    public static function regionAgent($model,$pay_type){
        $order_id = $model->id;
        $store = Store::where('id',$model->store_id)->first();
        if(!$store){
            return;
        }
        $storeId = $store->id;
        if($pay_type ==133){
            $config = DistrictAgentCommissionConfig::where('id',2)->first();
        }
        if($pay_type ==137){
            $config = DistrictAgentCommissionConfig::where('id',1)->first();
        }
        $fee = 1;
        if($config->is_discount==1){
            $fee = $fee*$config->discount_percentage/100;
        }
        if($config->is_pv==1){
            $fee = $fee*$config->pv_percentage/100;
        }
        $pAgentFee = $config->province_agent_commission*$fee/100;
        $cAgentFee = $config->city_agent_commission*$fee/100;
        $dAgentFee = $config->district_agent_commission*$fee/100;
        $pRecruiterFee = $config->province_recruiter_commission*$fee/100;
        $cRecruiterFee = $config->city_recruiter_commission*$fee/100;
        $dRecruiterFee = $config->district_recruiter_commission*$fee/100;
        $referrerFee = $config->merchant_referrer_commission*$fee/100;
        $groupFee = $config->county_group_percent*$fee/100;

        $provinceAgent = RegionProvinceAgent::select('ims_yz_region_province_agent.*')
        ->where('province_id',$store->province_id)
        ->join('ims_yz_region_agent', 'ims_yz_region_province_agent.region_id', '=', 'ims_yz_region_agent.id')
        ->where(function ($query) {
            $query->where('ims_yz_region_agent.levelId', 8);
          })
        ->first();
        $pagent_id = $provinceAgent?$provinceAgent->agent_id:0;//省代
        $precruiter_id = $provinceAgent?$provinceAgent->recruiter_id:0;//省招
        $cityAgent = RegionCityAgent::where(['city_id'=>$store->city_id,'levelId'=>8])->first();
        $cagent_id = $cityAgent?$cityAgent->agent_id:0;//市代
        $crecruiter_id = $cityAgent?$cityAgent->recruiter_id:0;//市招
        $districtAgent = RegionCityDistrictAgent::where(['district_id'=>$store->district_id,'levelId'=>8])->first();
        $dagent_id = $districtAgent?$districtAgent->agent_id:0;//区代
        $drecruiter_id = $districtAgent?$districtAgent->recruiter_id:0;//区招
        $recruiter_id = $store->recruiter_id; //门店推荐人
        if($config->is_merchant_commission == 1){//商家提成
            $merchant_id = $store->uid;
            $merchantFee = $config->merchant_commission_percentage*$fee/100;
            static::agentBill($pay_type,$merchantFee,$merchant_id,$storeId,12,$order_id);
        }
        $sdistrict_id = $store->district_id;
        $countyGroup = CountyGroup::where('levelId',8)->where(function ($query) use ($sdistrict_id) {
            $query->where('counties', 'like', '%'.$sdistrict_id.'%');
          })->first();
        $groupAgent_id = $countyGroup?$countyGroup ->agent_id:0; //组代理id
        $groupRecruiter_id = $countyGroup?$countyGroup ->recruiter_id:0; //组招募人id
        static::agentBill($pay_type,$pAgentFee,$pagent_id,$storeId,1,$order_id); //省代
        static::agentBill($pay_type,$cAgentFee,$cagent_id,$storeId,2,$order_id);//市代
        static::agentBill($pay_type,$dAgentFee,$dagent_id,$storeId,3,$order_id);//区代
        static::agentBill($pay_type,$pRecruiterFee,$precruiter_id,$storeId,4,$order_id,$pagent_id);//省招
        static::agentBill($pay_type,$cRecruiterFee,$crecruiter_id,$storeId,5,$order_id,$cagent_id);//市招
        static::agentBill($pay_type,$dRecruiterFee,$drecruiter_id,$storeId,6,$order_id,$dagent_id);//区招
        static::agentBill($pay_type,$referrerFee,$recruiter_id,$storeId,9,$order_id); //门店推荐人
        static::agentBill($pay_type,$groupFee,$groupAgent_id,$storeId,10,$order_id); //组代
        static::agentBill($pay_type,$groupFee,$groupRecruiter_id,$storeId,11,$order_id,$groupAgent_id); //组招
    }
    public static function agentBill($pay_type_id,$fee,$memberId,$storeId,$type,$order_id,$proffer_id=null)
    {//给代理分C款沐浴露

        $file = 'agentBill.txt';
            $fp = fopen($file, 'w');
            if (flock($fp, LOCK_EX)) {
                try {
                    // 执行需要同步的代码
                    $order = Order::where('id',$order_id)->first();
                    $price = $order->price;
                    $consume_id = $order->uid;
                    $order_sn = $order->order_sn;
                    $member = Member::where('uid',$memberId)->first();
                    if($member){
                        if($pay_type_id ==133){  //分茶包
                            $memberLove = MemberLove::where('member_id', $memberId)->first();
                            if($memberLove){
                                $usable = $memberLove->usable;
                                $newusable = $usable + $fee*$price;
                                MemberLove::where('member_id', $memberId)
                                ->update(['usable'=>$newusable]);
                            }
                        }
                        if($pay_type_id ==137){  //分沐浴露
                        $coin = $fee*$price;
                        if(!round($coin, 2)== 0.00){
                            $old_coin = 0;
                            $new_coin = 0;
                            $rece_user = BreedUserCoin::where(['user_id'=>$memberId,'consume_type'=>3])->first();
                            if($rece_user){
                                $rece_user_num = $rece_user->num;
                                $newcoin = $rece_user_num + $coin;
                                $old_coin = $rece_user_num;
                                $new_coin = $rece_user_num + $coin;
                                BreedUserCoin::where(['user_id'=>$memberId,'consume_type'=>3])->update(['num'=>$newcoin]);
                            }else{
                                $record = new BreedUserCoin(
                                ["uniacid"=>1, 'user_id' => $memberId,'consume_type'=>3,'num'=>$coin]
                                );
                                $new_coin = $coin;
                                $record->save();
                            }
                            $coin_flow_remark = config('constants.coin_flow_remark');
                            $remark = $coin_flow_remark[11];
                            if($type==10||$type==11){
                                $remark = '区域分组奖,商家ID:';
                            }
                            BreedCoinFlows::create(
                                ["uniacid"=>1,
                                'send_user' => 0,
                                'rec_user'=>$memberId,
                                'num'=>$coin,
                                'type'=>11,
                                'consume_type'=>3,
                                'old_coin'=>$old_coin,
                                'new_coin'=>$new_coin,
                                'remark'=>$remark.$storeId,
                                'created_at'=>time(),
                                'updated_at'=>time(),
                                ]
                            );
                            static::addCoinFlow($memberId,$consume_id,$coin,$storeId,$type,$old_coin,$new_coin,$price,$order_sn,$proffer_id);
                        }
                        }
                        
                    }
                } finally {
                    // 释放锁
                    flock($fp, LOCK_UN);
                    fclose($fp);
                }
            }
        
    }

    
    public static function addCoinFlow($benefit_id,$consume_id,$num,$storeId,$type,$old_coin,$new_coin,$price,$order_sn,$proffer_id=null)
    {
        $store = Store::where('id',$storeId)->first();
        $province_id = $store->province_id;
        $area = Area::where('id',$province_id)->first();
        $province_name = $area->areaname;
        $city_id = $store->city_id;
        $area = Area::where('id',$city_id)->first();
        $city_name = $area->areaname;
        $district_id = $store->district_id;
        $area = Area::where('id',$district_id)->first();
        $district_name = $area->areaname;
        $area = Area::where('id',request('parent_id'))->first();
        $coin_flow_remark = config('constants.coin_flow_remark');
        BreedCommissionCoinFlow::create(
                ["uniacid"=>1,
                 'type' => $type,
                 'consume_type'=>3,
                 'remark'=>$coin_flow_remark[11].$storeId,
                 'coin_type'=>1,
                 'store_id'=>$storeId,
                 'benefit_id'=>$benefit_id,
                 'consume_id'=>$consume_id,
                 'levelId'=>8,
                 'province_id'=>$province_id,
                 'province_name'=>$province_name,
                 'city_id'=>$city_id,
                 'city_name'=>$city_name,
                 'district_id'=>$district_id,
                 'district_name'=>$district_name,
                 'num'=>$num,
                 'old_coin'=>$old_coin,
                 'new_coin'=>$new_coin,
                 'price'=>$price,
                 'order_sn'=>$order_sn,
                 'proffer_id'=>$proffer_id,
                 'created_at'=>time(),
                 'updated_at'=>time(),
                 ]
        );
    }
}